import { store } from "@/store";

interface MyMessage {
  id: number;
  messageId: number;
  messageTitle: string;
  messageContent: string;
  messageLevel: number;
  targetType: number;
  publisherId: number;
  publisherName: string;
  publishTime: string;
  userId: number;
  userName: string;
  readStatus: number;
  readTime: string | null;
  createTime: string;
  createName: string;
  createUser: number;
  modifyTime: string;
  modifyName: string;
  modifyUser: number;
  isDelete: number;
}

export const useWebSocketStore = defineStore("websocket", () => {
  const state = reactive<{ messages: MyMessage[] }>({
    messages: [],
  });
  const readMessages = (messageId: number) => {
    const index = state.messages.findIndex((msg) => msg.messageId === messageId);
    //删除已读的消息
    if (index !== -1) {
      state.messages.splice(index, 1);
    }
    console.log("readMessages", state.messages);
  };
  const addMessage = (message: MyMessage) => {
    state.messages.push(message);
  };
  const clearMessages = () => {
    state.messages = [];
  };
  watch(
    () => state.messages,
    (newMessages) => {
      console.log("watch", newMessages);
    }
  );
  return {
    ...toRefs(state),
    readMessages,
    addMessage,
    clearMessages,
  };
});

/**
 * 用于在组件外部（如在Pinia Store 中）使用 Pinia 提供的 store 实例。
 * 官方文档解释了如何在组件外部使用 Pinia Store：
 * https://pinia.vuejs.org/core-concepts/outside-component-usage.html#using-a-store-outside-of-a-component
 */
export function useWebSocketStoreHook() {
  return useWebSocketStore(store);
}
